package com.renwei.yunlong.activity.work;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.TablayoutAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.HandleWorkBean;
import com.renwei.yunlong.bean.ReturnBean;
import com.renwei.yunlong.bean.UpdateUserIconBean;
import com.renwei.yunlong.event.WorkHandlerEvent;
import com.renwei.yunlong.event.WorkPageRefreshEvent;
import com.renwei.yunlong.fragment.PhotoUpdataFragment;
import com.renwei.yunlong.fragment.WorkHandlerFragment;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.SimpleOptionView;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import github.opensource.dialog.prompt.PromptButton;
import github.opensource.dialog.prompt.PromptButtonListener;
import github.opensource.dialog.prompt.PromptDialog;

public class WorkHandlerActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener, PromptButtonListener {

    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.tab_layout)
    TabLayout tabLayout;
    @Bind(R.id.view_pager)
    ViewPager viewPager;
    @Bind(R.id.bt_send_work)
    Button btSendWork;
    private WorkHandlerFragment workHandlerFragment;
    private PhotoUpdataFragment photoUpdataFragment;
    private String ownerCompanyCode;
    private String eventId;
    private String treatment;
    private String requestId;
    private PromptDialog promptDialog;
    private int type = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_work);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);

        EventBus.getDefault().register(this);
        requestId = getIntent().getStringExtra("requestId");
        eventId = getIntent().getStringExtra("eventId");
        ownerCompanyCode = getIntent().getStringExtra("ownerCompanyCode");
        treatment = getIntent().getStringExtra("treatment");

        initView();
        initData();
    }

    /**
     * 当前刷新
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onClose(WorkPageRefreshEvent event) {
        if (event.isFinish) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        simpleTileView.setTitle("处理工单");
        TextView titleView = simpleTileView.getTitleView();
        Drawable titleLeft = getResources().getDrawable(R.mipmap.icon_title_help);
        titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
        titleView.setCompoundDrawables(null, null, titleLeft, null);
        titleView.setCompoundDrawablePadding(10);

        btSendWork.setText("操作");
        titleView.setOnClickListener(this);
        btSendWork.setOnClickListener(this);
        promptDialog = new PromptDialog(this);

        String[] titles = {"基本信息", "添加附件"};
        List<Fragment> list = new ArrayList<>();
        workHandlerFragment = new WorkHandlerFragment(eventId, requestId, ownerCompanyCode);
        photoUpdataFragment = new PhotoUpdataFragment(true);
        list.add(workHandlerFragment);
        list.add(photoUpdataFragment);

        TablayoutAdapter adapter = new TablayoutAdapter(getSupportFragmentManager(), list, titles);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {//业主
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            map.put("eventid", eventId);
            map.put("requestId", requestId);
        } else if ("2".equals(companyType)) {//服务商
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("eventid", eventId);
            map.put("requestId", requestId);
        }
        ServiceRequestManager.getManager().getWorkHandler(this, JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_send_work:
                PromptButton cancle = new PromptButton("取消", null);
                promptDialog.showAlertSheet("", true, cancle,
                        new PromptButton("暂存草稿", this),
                        new PromptButton("保存记录", this),
                        new PromptButton("处理完成", this));

                break;
            case R.id.option_textview_title:
                GuideWebActivity.openActivity(this, Api.$().GUIDE_DEAL_WORK_URI);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(PromptButton button) {
        HashMap<String, String> map = workHandlerFragment.getHandlerData();
        if (map == null || map.size() == 0) {
            return;
        }
        List<UpdateUserIconBean> photoInfo = photoUpdataFragment.getPhotoInfo();
        // 图片上传
        String filenames = "";
        String attachPath = "";
        String attachSize = "";
        for (int i = 0; i < photoInfo.size(); i++) {
            UpdateUserIconBean photo = photoInfo.get(i);
            if (i == photoInfo.size() - 1) {
                filenames += photo.getName();
                attachPath += photo.getPath();
                attachSize += photo.getSize();
            } else {
                filenames += photo.getName() + ",";
                attachPath += photo.getPath() + ",";
                attachSize += photo.getSize() + ",";
            }
        }
        map.put("attachName", filenames);
        map.put("attachPath", attachPath);
        map.put("attachSize", attachSize);

        switch (button.getText()) {
            case "暂存草稿":
                type = 0;
                map.put("type", "0");
                ServiceRequestManager.getManager().setWorkHandler(this, JsonMapUtil.mapToJson(map), this);
                break;
            case "保存记录":
                type = 1;
                map.put("type", "1");
                ServiceRequestManager.getManager().setWorkHandler(this, JsonMapUtil.mapToJson(map), this);
                break;
            case "处理完成":
                type = 2;
                map.put("type", "2");
                if ("1".equals(treatment)) {
                    // 跳转到签名界面
                    WorkHandleDesignActivity.OpenActivity(mContext, map);
                } else {
                    ServiceRequestManager.getManager().setWorkHandler(this, JsonMapUtil.mapToJson(map), this);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                HandleWorkBean handleWorkBean = new Gson().fromJson(result, HandleWorkBean.class);
                EventBus.getDefault().post(new WorkHandlerEvent(handleWorkBean));
                break;
            case 2:
                ReturnBean bean = new Gson().fromJson(result, ReturnBean.class);
                if (bean.getMessage().getCode() == 200) {
                    if (type == 2) {
                        //工单处理完成 签名绘制
                        EventBus.getDefault().post(new WorkPageRefreshEvent(true));
                    } else if (type == 0) {
                        //  草稿
                        EventBus.getDefault().post(new WorkPageRefreshEvent());
                    } else if (type == 1) {
                        // 保存记录
                        EventBus.getDefault().post(new WorkPageRefreshEvent());
                    }
                    showCenterSuccessMsg("操作成功");
                    finish();
                } else if (bean.getMessage().getCode() == 1004) {
                    showCenterInfoMsg("数据不存在");
                } else {
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }

    public static void OpenActivity(Context context, String requestId, String eventId, String ownerCompanyCode, String treatment) {
        Intent i = new Intent(context, WorkHandlerActivity.class);
        i.putExtra("requestId", requestId);
        i.putExtra("ownerCompanyCode", ownerCompanyCode);
        i.putExtra("eventId", eventId);
        i.putExtra("treatment", treatment);
        context.startActivity(i);
    }

}
